package org.algorithm.Backtracking.leetcode90;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {

    /**
     * 子集问题，输入的数组中含有重复元素，需要横向考虑数据重复
     */

    List<List<Integer>> res = new ArrayList<>();
    List<Integer> item = new ArrayList<>();

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        boolean[] used = new boolean[nums.length];
        Arrays.sort(nums);
        Arrays.fill(used, false);
        backtracking(nums, used, 0);
        return res;
    }

    private void backtracking(int[] nums, boolean[] used, int index) {


        res.add(new ArrayList<>(item));

        for (int i = index; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
                continue;
            }
            item.add(nums[i]);
            used[i] = true;
            backtracking(nums, used, i + 1);

            item.remove(item.size() - 1);
            used[i] = false;
        }
    }
}
